﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.Routing;
using System.Reflection;

namespace SimpleRest.Core.Routing.Handlers
{
    /// <summary>
    /// The route handler that is used within the RouteBase that sits as a proxy to the operation http handler from the operation route.
    /// </summary>
    public class RouteHandler : IRouteHandler
    {
        private readonly string RouteUri;

        protected RouteHandler() { }
        public RouteHandler(string routeUri)
            : base()
        {
            this.RouteUri = routeUri;
        }

        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            string incomingMethod = requestContext.HttpContext.Request.HttpMethod;

            // search for exact route match.
            var operationRoute =
                RouteUtility.GetRegisteredOperations().FirstOrDefault(
                d => d.Route.Url.ToLower().Trim(new char[] { '/', '\\', ' ' }) == this.RouteUri.ToLower().Trim(new char[] { '/', '\\', ' ' }) &&
                    d.HttpMethod.ToLower() == incomingMethod.ToLower());

            if (operationRoute != null)
            {
                IHttpRequestMessage requestMessage = new HttpRequestMessage(requestContext);
                RouteUtility.raiseIncomingRequest(requestContext, requestMessage);
                return new OperationHttpHandler(new Pipeline(operationRoute.ServiceType), requestContext, operationRoute.TargetMethod, operationRoute.Configuration, requestMessage);
            }
            else
                return new UriNotFoundHttpHandler(this.RouteUri);
        }
    }
}
